package com.higgins.eventtracking.server;

import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.higgins.eventtracking.client.SecurityAccessDeniedException;
import com.google.appengine.api.log.*;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GenericDataStoreService extends RemoteServiceServlet	{
	protected PersistenceManager pm;
	protected boolean testMode = false;
	private static final Logger log = Logger.getLogger(GenericDataStoreService.class.getName());
	
	public void openPersistenceManager()	{
		pm=PMF.get().getPersistenceManager();
	}
	public void closePersistenceManager()	{
		pm.close();
	}
	public void setTestMode()	{
		testMode = true;
	}
	public void checkAuthority() throws SecurityAccessDeniedException	{
		UserService userService = UserServiceFactory.getUserService();
		User currentUser = userService.getCurrentUser();
		String emailAddress = "PSHiggins@gmail.com";
		emailAddress = emailAddress.toLowerCase();
		if ((currentUser!=null) && (currentUser.getEmail().toLowerCase().contains(emailAddress) || currentUser.getEmail().toLowerCase().contains("test@example.com")))	{
			log.info(currentUser.getEmail());
			log.info("Access Granted");		
		}	else if (!testMode)	{
			log.severe("User ID: " + currentUser.getUserId());
			log.severe("User Email: " + currentUser.getEmail());
			log.severe("SecurityAccessDeniedException");
			throw new SecurityAccessDeniedException();	
		}	else if (testMode)	{
//			log.info(currentUser.getEmail());
			log.info("Access Granted");
		}
	}
}
